use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::Path;

/// 工具类 `FileUtil` 用于处理文件相关操作
pub struct FileUtil;

impl FileUtil {
    /// 读取文件内容到字符串
    ///
    /// # 参数
    /// * `path` - 文件路径
    ///
    /// # 返回值
    /// 返回包含文件内容的 `Result<String, io::Error>`
    ///
    /// # 示例
    /// ```
    /// let content = FileUtil::read_to_string("example.txt");
    /// match content {
    ///     Ok(text) => log::info!("File content: {}", text),
    ///     Err(e) => log::info!("Error reading file: {}", e),
    /// }
    /// ```
    pub fn read_to_string(path: &str) -> Result<String, io::Error> {
        fs::read_to_string(path)
    }

    /// 将字符串内容写入文件
    ///
    /// # 参数
    /// * `path` - 文件路径
    /// * `content` - 要写入的内容
    ///
    /// # 返回值
    /// 返回一个 `Result<(), io::Error>`
    ///
    /// # 示例
    /// ```
    /// match FileUtil::write_string("example.txt", "Hello, world!") {
    ///     Ok(_) => log::info!("File written successfully."),
    ///     Err(e) => log::info!("Failed to write file: {}", e),
    /// }
    /// ```
    pub fn write_string(path: &str, content: &str) -> Result<(), io::Error> {
        fs::write(path, content)
    }

    /// 追加字符串内容到文件
    ///
    /// # 参数
    /// * `path` - 文件路径
    /// * `content` - 要追加的内容
    ///
    /// # 返回值
    /// 返回一个 `Result<(), io::Error>`
    ///
    /// # 示例
    /// ```
    /// match FileUtil::append_string("example.txt", "\nAppended content.") {
    ///     Ok(_) => log::info!("Content appended successfully."),
    ///     Err(e) => log::info!("Failed to append content: {}", e),
    /// }
    /// ```
    pub fn append_string(path: &str, content: &str) -> Result<(), io::Error> {
        let mut file = OpenOptions::new().append(true).open(path)?;
        file.write_all(content.as_bytes())
    }

    /// 拷贝文件
    ///
    /// # 参数
    /// * `src` - 源文件路径
    /// * `dst` - 目标文件路径
    ///
    /// # 返回值
    /// 返回一个 `Result<u64, io::Error>`，表示拷贝的字节数
    ///
    /// # 示例
    /// ```
    /// match FileUtil::copy("example.txt", "example_copy.txt") {
    ///     Ok(bytes) => log::info!("Copied {} bytes.", bytes),
    ///     Err(e) => log::info!("Failed to copy file: {}", e),
    /// }
    /// ```
    pub fn copy(src: &str, dst: &str) -> Result<u64, io::Error> {
        fs::copy(src, dst)
    }

    /// 删除文件
    ///
    /// # 参数
    /// * `path` - 文件路径
    ///
    /// # 返回值
    /// 返回一个 `Result<(), io::Error>`
    ///
    /// # 示例
    /// ```
    /// match FileUtil::delete("example.txt") {
    ///     Ok(_) => log::info!("File deleted successfully."),
    ///     Err(e) => log::info!("Failed to delete file: {}", e),
    /// }
    /// ```
    pub fn delete(path: &str) -> Result<(), io::Error> {
        fs::remove_file(path)
    }

    /// 创建新文件
    ///
    /// # 参数
    /// * `path` - 文件路径
    ///
    /// # 返回值
    /// 返回一个包含文件句柄的 `Result<File, io::Error>`
    ///
    /// # 示例
    /// ```
    /// match FileUtil::create("new_file.txt") {
    ///     Ok(file) => log::info!("File created successfully."),
    ///     Err(e) => log::info!("Failed to create file: {}", e),
    /// }
    /// ```
    pub fn create(path: &str) -> Result<File, io::Error> {
        File::create(path)
    }

    /// 打开文件进行读取
    ///
    /// # 参数
    /// * `path` - 文件路径
    ///
    /// # 返回值
    /// 返回一个包含文件句柄的 `Result<File, io::Error>`
    ///
    /// # 示例
    /// ```
    /// match FileUtil::open("example.txt") {
    ///     Ok(file) => log::info!("File opened successfully."),
    ///     Err(e) => log::info!("Failed to open file: {}", e),
    /// }
    /// ```
    pub fn open(path: &str) -> Result<File, io::Error> {
        File::open(path)
    }

    /// 检查文件是否存在
    ///
    /// # 参数
    /// * `path` - 文件路径
    ///
    /// # 返回值
    /// 如果文件存在则返回 `true`，否则返回 `false`
    ///
    /// # 示例
    /// ```
    /// let file_exists = FileUtil::exists("example.txt");
    /// log::info!("File exists: {}", file_exists);
    /// ```
    pub fn exists(path: &str) -> bool {
        Path::new(path).exists()
    }

    /// 创建目录（包括所有上级目录）
    ///
    /// # 参数
    /// * `path` - 目录路径
    ///
    /// # 返回值
    /// 返回一个 `Result<(), io::Error>`
    ///
    /// # 示例
    /// ```
    /// match FileUtil::create_dir_all("example_dir/sub_dir") {
    ///     Ok(_) => log::info!("Directories created successfully."),
    ///     Err(e) => log::info!("Failed to create directories: {}", e),
    /// }
    /// ```
    pub fn create_dir_all(path: &str) -> Result<(), io::Error> {
        fs::create_dir_all(path)
    }

    /// 列出目录中的所有文件和子目录
    ///
    /// # 参数
    /// * `path` - 目录路径
    ///
    /// # 返回值
    /// 返回包含路径的 `Result<Vec<String>, io::Error>`
    ///
    /// # 示例
    /// ```
    /// match FileUtil::read_dir("example_dir") {
    ///     Ok(entries) => {
    ///         for entry in entries {
    ///             log::info!("Directory entry: {}", entry);
    ///         }
    ///     }
    ///     Err(e) => log::info!("Failed to read directory: {}", e),
    /// }
    /// ```
    pub fn read_dir(path: &str) -> Result<Vec<String>, io::Error> {
        let entries = fs::read_dir(path)?
            .filter_map(|entry| entry.ok())
            .map(|entry| entry.path().to_string_lossy().to_string())
            .collect();
        Ok(entries)
    }
}

fn main() {
    let path = "example.txt";
    let content = "Hello, world!";

    // 写入文件
    match FileUtil::write_string(path, content) {
        Ok(_) => log::info!("File written successfully."),
        Err(e) => log::info!("Failed to write file: {}", e),
    }

    // 读取文件内容
    match FileUtil::read_to_string(path) {
        Ok(content) => log::info!("File content: {}", content),
        Err(e) => log::info!("Failed to read file: {}", e),
    }

    // 追加内容到文件
    match FileUtil::append_string(path, "\nAppended content.") {
        Ok(_) => log::info!("Content appended successfully."),
        Err(e) => log::info!("Failed to append content: {}", e),
    }

    // 检查文件是否存在
    if FileUtil::exists(path) {
        log::info!("File exists.");
    } else {
        log::info!("File does not exist.");
    }

    // 删除文件
    match FileUtil::delete(path) {
        Ok(_) => log::info!("File deleted successfully."),
        Err(e) => log::info!("Failed to delete file: {}", e),
    }

    // 创建目录
    match FileUtil::create_dir_all("example_dir") {
        Ok(_) => log::info!("Directory created successfully."),
        Err(e) => log::info!("Failed to create directory: {}", e),
    }

    // 列出目录内容
    match FileUtil::read_dir(".") {
        Ok(entries) => {
            for entry in entries {
                log::info!("Directory entry: {}", entry);
            }
        }
        Err(e) => log::info!("Failed to read directory: {}", e),
    }
}